﻿using System;
using System.Linq;
using CRM.Database.Model;

namespace CRM.Syncroniser
{
 public    class SapLegalEntitiesSyncronisation:ISyncronise
    {
     #region Implementation of ISyncronise

     /// <summary>
     /// Запуск синхронизации
     /// </summary>
     /// <returns>Результат запуска</returns>
     public bool Syncronise()
     {
         var entities = new CRM.Database.Model.CRMEntities();
         var agrCol = new AgreementElementsCollection();
         var leCol= new LegalEntitiesCollection();
         foreach (var item in entities.SapLegalEntities.ToList())
         {
             /*Сначала попробуем найти юр. лицо по номеру САП*/

             var le = leCol.GetLegalEntityBySapNumber(Convert.ToInt32(item.Дебитор));

             if(le!=null)
             {
                 if(le.Name!=item.Имя_1)
                 {
                     le.Name = item.Имя_1;
                     leCol.Update(le, "Max"+DateTime.Now.ToShortDateString());
                 }

                 string[] names = item.Имя_1.Split(' ');

                 if(names[0]!=null)
                 {
                     int idOwnershipPattern = 0;
                     var oCol = new OwnershipsPatternsCollection();

                     foreach(var ownershipName in names)
                     {
                         idOwnershipPattern = oCol.GetIdByName(ownershipName);

                         if(idOwnershipPattern==0)
                         {
                             
                         }
                         if(idOwnershipPattern>0)
                         {
                             if (le.IdOwnershipPattern == 0 | le.IdOwnershipPattern==null)
                             {
                                 le.IdOwnershipPattern = idOwnershipPattern;
                                 le.ShortName = item.Имя_1.Replace(ownershipName, "");
                                 leCol.Update(le, "Max" + DateTime.Now.ToShortDateString());
                             }

                             if(le.AgreementElements.Count==0)
                           {
                               var agr = new AgreementElements();

                               agr.IdLegalEntity = le.IdLegalEntity;
                               agr.FullAddress = item.П_индекс+", " + item.Город +", "+ item.Улица;
                               agr.INN = item.РегНалогНомер_1;
                               agr.KPP = item.Налоговый_номер_3;
                               if (string.IsNullOrEmpty(agr.KPP)) 
                                   agr.KPP = "-";
                               agr.RS = item.КК + item.Банковский_счет;
                               if (!string.IsNullOrEmpty(item.Филиал_банка)) agr.KS = item.Филиал_банка.Remove(item.Филиал_банка.Length - 1);
                               if (string.IsNullOrEmpty(item.Филиал_банка)) agr.KS = "-";
                               agr.BIK = item.Ключ_банка;
                               agr.Bank = item.Название_финансово_кредитного;
                               agr.OKPO = item.РегНалНомер_2;
                               agr.PostIndex = item.П_индекс;
                               if (string.IsNullOrEmpty(agr.PostIndex))
                                   agr.PostIndex = "000000";
                               agr.FIOGenDirExt = "-";
                               agr.FIOGenDirInRPExt = "-";
                               agr.OGRNExt = "-";

                               agrCol.Add(agr, "Max" + DateTime.Now.ToShortDateString());
                           }


                             break;
                         }
                     }

                    
                 }
             }

             /********************************/
         }


         return true;
     }

     #endregion
    }
}
